﻿using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Common.Lib.Assembly;
using NHibernate.Util;

namespace NHibernate.MsSqlCe
{
    public class NHibernateMsSqlCeDatabaseTester : NHibernateMsSqlCeVirtualDatabaseEnvironment
    {
        NHibernateMsSqlCeDatabaseInfo _defaultInfo;
        public NHibernateMsSqlCeDatabaseTester()
        {
            Dictionary<string, string> properties = ConfigurationUtil.GetDefaultProperties();
            properties.Add(NHibernate.Cfg.Environment.ConnectionProvider, typeof(MultiUserSingleConnectionProvider).AssemblyQualifiedName);
            _defaultInfo = new NHibernateMsSqlCeDatabaseInfo()
            {
                DatabasePath = Directory.GetCurrentDirectory() + "\\" + "test.sdf",
                Encrypted = false,
                Password = "",
                Properties = properties
            };
        }

        public void Start(Dictionary<string, IEnumerable<string>> resources)
        {
            if (File.Exists(_defaultInfo.DatabasePath))
            {
                File.Delete(_defaultInfo.DatabasePath);
            }
            _defaultInfo.Resources = resources;
            base.Start(_defaultInfo);
        }

        public void Start(params AssemblyResourceCollection[] collections)
        {
            Dictionary<string, IEnumerable<string>> resources = new Dictionary<string, IEnumerable<string>>();
            if (collections != null && collections.Count() > 0)
            {
                foreach (var collection in collections)
                {
                    List<string> fileList = new List<string>();
                    resources.Add(collection.AssemblyName, fileList);
                    foreach (var res in collection)
                    {
                        fileList.Add(res.QualifiedResourcePath);
                    }
                }
            }
            Start(resources);
        }

        public int GetCount<T>()
        {
            return GetUnitWorker(null).Count<T>(_ => true);
        }

        public void Save(params object[] saveList)
        {
            GetUnitWorker(null).DoUnitOfWork<object>(dao =>
            {
                dao.Save(saveList);
                return null;
            });
        }

        public void Delete(params object[] saveList)
        {
            GetUnitWorker(null).DoUnitOfWork<object>(dao =>
            {
                dao.Delete(saveList);
                return null;
            });
        }

        public T Get<T>(object id)
        {
            return GetUnitWorker(null).DoUnitOfWork<T>(dao => dao.Get<T>(id));
        }

        public List<T> List<T>(Func<T, bool> predicate)
        {
            return GetUnitWorker(null).DoUnitOfWork<List<T>>(
                dao => dao.List<T>(predicate).ToList());
        }

    }
}
